var io = require('socket.io');
var http = require("http");
var url = require('url');
var qs = require('querystring');
var map = {};

var server = http.createServer(function (req, res) {
    if (!isValid(url.parse(req.url).pathname)) {
        res.writeHead(404, {'Content-Type': 'text/plain;charset=utf-8'});
        res.write("{'errcode':404,'errmsg':'请求不在定义范围内'}");
        res.end();
    } else {
        res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
        if (req.method.toUpperCase() == 'POST') {
            var postData = "";
            req.addListener("data", function (data) {
                postData += data;
            });
            req.addListener("end", function () {
                var query = qs.parse(postData);
                writeOut(query, res);
            });
        }
    }
});
server.listen(3000);
sockets = io.listen(server);

var route = {
    '/': "/",
    '/dashboard/assign_request': '/dashboard/assign_request'
};

var isValid = function (reqPath) {
    for (var key in route) {
        if (route[key] == reqPath) {
            return true;
        }
    }
    return false;
};

var writeOut = function (query, res) {
    var str = JSON.stringify(query);
    var obj = JSON.parse(str);
    var socket = map[obj.adminid];
    if (typeof(socket) != "undefined") {
        console.log(obj.adminid);
        socket.emit('assign_push',{
          data: JSON.stringify(query)
        });
    }
    res.end();
}

sockets.on('connection', function (socket) {
     var socketId = socket.id;

     socket.emit('link_success', {});

     socket.on('join', function (data) {
        console.log("网销ID:"+data.adminId + "建立连接");
        map[data.adminId] = socket;
     });

     socket.on('disconnect', function () {
        console.log(socketId + "用户退出链接");
     });

});